
<template>
  <div id="emergencyMonitor" class="wrapper">
    <!--- 左侧查询面板-->
    <div class="expandBtn" @click="letDrawerControl = true">
      <img src="@/assets/icons/grow.png" alt="O" class="iconBtn" />
    </div>
    <detailLeftDrawer
      ref="detailLeftDrawer"
      :map="map"
      :img_L4="img_L4"
      :shp_L5="shp_L5"
      :afterMap="afterMap"
      :modelShow="letDrawerControl"
      @refreshRegion="refreshRegion"
      @leftDrawerHide="letDrawerControl = false"
      @drawGeometry="drawGeometry"
      @drawRectangle="drawRectangle"
      @removeRegionLayer="removeLayer"
      @drawPoly="drawPolygon"
      @updateDir="updateDir"
      @upDateLeaf="upDateLeaf"
      @dataPart="dataPart"
      @updateNDVI="updateNDVI"
      @updateLST="updateLST"
      @isLoading="isLoadingEvent"
      @taskName="getTaskName"
      @dataList="dataList"
    />
    <!-- :currentDrawGeometry1="currentDrawGeometry" -->

    <!--- 地图区域-->
    <div class="dpMapControllWrapper">
      <div class="topButton">
        <div>
          <Button
            shape="circle"
            icon="ios-square-outline"
            @click="drawRectangle"
            title="绘制矩形"
            style="margin-right: 6px"
          >
          </Button>
          <Button
            shape="circle"
            icon="ios-crop"
            @click="drawPolygon"
            title="绘制多边形"
            style="margin-right: 6px"
          >
          </Button>

          <Button
            shape="circle"
            icon="ios-trash-outline"
            title="删除标签,单击选中或快捷键shift绘制范围选中的标签"
            @click="delSelectedFeatures"
            style="margin-right: 6px"
          >
          </Button>
        </div>
      </div>
      <div class="taskNameDiv">{{ taskName }}</div>
      <div id="beforeMap" ref="themap" class="map"></div>
      <div class="info">{{ coordinateInfo }}</div>
      <div id="afterMap" class="map"></div>
      <div id="wrapper"></div>
    </div>

    <!--- 任务列表区域-->
    <div @click="taskControl = true" class="taskImg">
      <img src="@/assets/icons/grow.png" alt="O" class="iconBtn1" />
    </div>
    <Card :class="letDrawerControl ? 'no-expand' : ''">
      <detailTaskArea
        :modelShow="taskControl"
        @taskControlHide="taskControl = false"
        @dotImgAndShp="dotImgAndShp"
        :nodeSelectLeaf="updateLeaf"
        :map="map"
        :leftDataList="leftDataList"
        :afterMap="afterMap"
        @aux="aux"
      />
    </Card>

    <!--- 监测任务功能区-->
    <detailMonitorProduct @produce="produce" />
    <detailProduceTask
      ref="detailProduceTask"
      :showPopup="showPopup"
      :imgDir="imgDir"
      :imgNDVI="imgNDVI"
      :imgLST="imgLST"
      :dataPartValue="dataPartValue"
      @hideForm="showPopup = false"
      @treeFile="openTreeFile"
    />
    <Spin fix v-if="isLoading">
      <Icon type="ios-loading" size="80" class="demo-spin-icon-load"></Icon>
      <div>{{ loadingText }}</div>
    </Spin>
    <!-- 添加树节点 -->
    <Modal
      v-model="setFeatureNameModal"
      draggable
      scrollable
      :closable="false"
      title="设置绘制范围名称："
    >
      <Input v-model="featureName" placeholder="请输入范围名称" />
      <template #footer class="footerBtns">
        <CButton @click="cancelFeatrueSave" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="setFeatureNameOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
    <Modal
      v-model="deleteConfirm"
      draggable
      scrollable
      width="600"
      title="删除区域"
      class="addStyle"
    >
      <p slot="header" class="modalHeader">
        <span style="margin-left: 5px">删除样本标签</span>
      </p>
      <div style="margin-left: 10px">
        <p>是否删除所选中的区域?</p>
      </div>
      <template #footer class="footerBtns">
        <CButton @click="deleteConfirm = false" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="delFeatureBtn" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
  </div>
</template>

<script>
import Axios from "axios";
import { Spin } from "iview";
import detailTaskArea from "./detailTaskArea.vue";
import detailMonitorProduct from "./detailMonitorProduct.vue";
import detailProduceTask from "./detailProduceTask.vue";
import detailLeftDrawer from "./detailLeftDrawer.vue";

export default {
  name: "detailTaskRegularRisk",
  components: {
    detailTaskArea,
    detailMonitorProduct,
    detailProduceTask,
    detailLeftDrawer,
  },
  data() {
    return {
      img_L4: [],
      shp_L5: {},
      leftDataList: [],
      taskName: "",
      coordinateInfo: "",
      customFeature: [],
      beforeMap: null,
      afterMap: null,
      compare: null,
      isHorizontal: false,
      isLoading: false,
      loadingText: "正在加载，请稍后~",
      deleteConfirm: false,
      setFeatureNameModal: false,
      featureName: "",
      timer: "",
      map: null,
      letDrawerControl: true,
      taskControl: true,
      bottomOpen: true,
      showPopup: false,
      treeDataControl: false,
      // TODO: this should be a param coming from router url.
      taskId: -1,
      riskId: -1,
      // TODO: this should be sync with data tree, path + url.
      imgDir: [],
      updateLeaf: [],
      imgNDVI: [],
      imgLST: [],
      dataPartValue: "",
      currentDrawGeometry: [],
      // isUpdateRegionResultAndSave: false, //更新左侧树的区域结果以参数保存
    };
  },
  mounted() {
    this.taskId = this.$route.query.id;
    this.initmap();
    this.initDrawTool();
    this.riskId = this.$route.query.id;
    // this.queryTask();
    // this.gettestMap();
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.resizeMap();
    }, 200);
  },
  methods: {
    aux() {
      debugger;
      console.log(this.img_L4, this.shp_L5, "this.shp_L5");
      this.$refs.detailLeftDrawer.getSatalliteTreeList1(
        this.img_L4,
        this.shp_L5
      );
    },
    //获得火点显示的影像和矢量数据
    dotImgAndShp(value, value1) {
      this.img_L4 = value;
      this.shp_L5 = value1;
    },

    refreshRegion() {
      this.$refs.detailProduceTask.getRegionResultId();
    },
    dataList(value) {
      this.leftDataList = value;
    },
    getImgView() {
      this.$refs.detailLeftDrawer.getInfo();
    },
    getTaskName(name) {
      this.taskName = name;
    },
    resizeMap() {
      let _this = this;
      _this.beforeMap.resize()._update(); //更新页面
      _this.afterMap.resize()._update();
    },
    openTreeFile(val) {
      this.$refs.detailLeftDrawer.openTreeData(val);
      //this.showPopup=false;
    },

    isLoadingEvent() {},
    test() {
      this.map.addLayer({
        id: "imageServe",
        source: {
          type: "raster",
          tiles: [
            'http://161.189.141.168:38199/v1?request=GetTile&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&info={"info":[{"path":"/data/test_data/GF1_1.tif"}]}',
          ],
        },
        layout: { visibility: "visible" },
        "source-layer": "imageServe",
      });
    },
    gettestMap() {
      let path = "http://172.16.40.43:10005/v1?request=GetImageInfo"; //http:172.16.40.43:1005?request=RegisterImageIdInfo
      let param = ["/pie/data/cfu/GF1_1.tif"];
      this.http.post(path, param).then((res) => {});
    },
    // async queryTask() {
    //   const path = this.$api.emergencyMonitorApi.queryTaskWithId;
    //   const { data } = await Axios.get(path + this.taskId);
    //   if (!data || data.code !== 200)
    //     this.$Message.warning("通过任务id获取任务信息失败");
    //   else {
    //     this.disasterId = data.data.disasterId;
    //   }
    // },

    /**---------地图操作--------**/
    initmap() {
      let _this = this;
      let style = "";
      if (this.taskId == 1) {
        style = "./static/map/riskMap.json";
      } else {
        style="./static/map/map.json";
      }
      this.beforeMap = new mapboxgl.Map({
        container: "beforeMap", // container id
        style: style,
        center: [106.4, 24.5],
        zoom: 3, // starting zoom
        minZoom: 3,
        epsg: 3857,
        doubleClickZoom: false,
      });

      _this.map = _this.beforeMap;
      this.beforeMap.addControl(new mapboxgl.FullscreenControl()); //全图显示
      this.beforeMap.addControl(new mapboxgl.NavigationControl()); //导航栏
      var scale = new mapboxgl.ScaleControl({
        maxWidth: 80,
        unit: "metric",
      });
      this.beforeMap.addControl(scale);
      this.beforeMap.on("load", () => {
        // this.resizeMap();
      });
      this.afterMap = new mapboxgl.Map({
        container: "afterMap",
        style: style,
        center: [106.4, 24.5],
        zoom: 3, // starting zoom
        minZoom: 3,
        epsg: 3857,
      });

      _this.compare = new mapboxgl.Compare(
        _this.beforeMap,
        _this.afterMap,
        "#wrapper",
        {
          // moussemove: true,
          orientation: _this.isHorizontal ? "horizontal" : "vertical",
        }
      );
      _this.compare.setSlider(2800); //设置中间卷帘线的位置
      this.beforeMap.on("mousemove", (e) => {
        _this.coordinateInfo =
          "经度：" +
          parseFloat(e.lngLat.lng).toFixed(3) +
          "   纬度：" +
          parseFloat(e.lngLat.lat).toFixed(3);
      });
    },
    switchOrientation() {
      let _this = this;
      _this.compare.remove();
      _this.isHorizontal = !_this.isHorizontal;
      _this.compare = new mapboxgl.Compare(
        _this.beforeMap,
        _this.afterMap,
        "#wrapper",
        {
          // moussemove: true,
          orientation: _this.isHorizontal ? "horizontal" : "vertical",
        }
      );
    },
    // 添加框选
    initDrawTool() {
      let _this = this;
      var modes = MapboxDraw.modes;
      modes.draw_rectangle = DrawRectangle.default;
      this.draw = new MapboxDraw({
        modes: modes,
        displayControlsDefault: false,
      });

      this.map.addControl(this.draw, "top-right"); // 添加插件
      this.map.on("draw.create", function (feature) {
        _this.setFeatureNameModal = true;
        _this.currentDrawGeometry = feature.features;
        // this.currentDrawGeometry = _this.draw.getAll().features;
        // let data = {
        //   leftTopLat: feature.features[0].geometry.coordinates[0][0][0],
        //   leftTopLong: feature.features[0].geometry.coordinates[0][1][1],
        //   rightBottomLat: feature.features[0].geometry.coordinates[0][2][0],
        //   rightBottomLong: feature.features[0].geometry.coordinates[0][2][1],
        // };
        // _this.$emit("update:latitudeLongitude", data);
        // _this.$emit("computer", _this.draw.getAll().features);
      });
      this.map.on("draw.delete", function (feature) {});
    },
    delFeatureBtn() {
      this.deleteConfirm = false;
      let selectFeatures = this.draw.getSelected();
      let ids = this.draw.getSelectedIds();
      this.deleteAssociateArea(ids);
    },

    setFeatureNameOk() {
      let _this = this;
      if (!_this.featureName) {
        _this.$Message.warning("区域名称不能为空，请先设置！");
        return;
      }
      _this.addAssociateArea(_this.currentDrawGeometry);
    },
    async geoJsonToWkt(geojson) {
      let wkt = "";
      let path = this.$api.emergencyMonitorApi.geoJsonToWkt;
      await this.http.post(path, geojson).then((res) => {
        if (res.data.success) {
          wkt = res.data.data;
        } else {
          this.$Message.error("wkt转换失败");
        }
      });
      return wkt;
    },
    //地图自定义绘制features保存
    async addAssociateArea(features) {
      // let wkt = await this.geoJsonToWkt(features[0].geometry);
      // this.$refs.detailLeftDrawer.getcustomRegeion(wkt,this.featureName)
      // this.setFeatureNameModal = false;
      let _this = this;
      let path = this.$api.riskMonitorApi.addAssociateArea;
      let wkt = await this.geoJsonToWkt(features[0].geometry);

      let param = {
        disasterTaskId: this.taskId,
        // regionCode: 0, 自定义不用填
        regionName: _this.featureName, //绘制区域自定义名称
        regionType: 1, //1,表示自定义区域  0 ：表示区划
        regionWkt: wkt,
        taskSource: 12,
      };

      this.http.post(path, param).then((res) => {
        if (res.data.success) {
          _this.setFeatureNameModal = false;
          _this.$refs.detailLeftDrawer.updateRegionResultAndSave();
          _this.$refs.detailProduceTask.getRegionResultId();
          this.$Message.info("绘制范围保存成功");
        } else {
          this.$Message.error("范围保存失败," + res.data.message);
        }
      });
    },
    //取消要素保存
    cancelFeatrueSave() {
      this.setFeatureNameModal = false;
      this.draw.delete(this.currentDrawGeometry[0].id);
    },
    deleteAssociateArea(ids) {
      let _this = this;
      _this.draw.delete(ids);
      let path = this.$api.emergencyMonitorApi.deleteAssociateArea + ids;
      this.http.post(path).then((res) => {
        if (res.data.success) {
          _this.draw.delete(ids);
          _this.$refs.detailLeftDrawer.updateRegionResultAndSave();
          _this.$refs.detailProduceTask.getRegionResultId();
          this.$Message.info("范围删除成功");
        } else {
          this.$Message.error("删除失败");
        }
      });
    },

    getCurrentDrawGeometry() {
      return this.draw.getAll().features;
    },
    // 绘制矩形
    drawRectangle() {
      // this.draw.deleteAll();
      this.draw.changeMode("draw_rectangle");
    },
    // 绘制多边形
    drawPolygon() {
      this.draw.changeMode("draw_polygon");
    },
    delSelectedFeatures() {
      // 选中所有要素
      this.deleteConfirm = true;
    },
    //根据范围渲染地图矢量范围
    removeAllImages() {
      let _this = this;
      let allLayer = _this.map.getStyle().layers;

      let filter = "";
      //基础表和结果表不同时删除，例如在基础表页删除全部图层时要保留结果表图层
      if (_this.tabValue === "base") {
        filter = "result_img";
      }
      if (_this.tabValue === "result") {
        filter = "base_img";
      }
      for (let i = 0; i < allLayer.length; i++) {
        if (
          allLayer[i].type === "raster" &&
          allLayer[i].id != "imgtest" &&
          !allLayer[i].id.includes(filter)
        )
          _this.removeLayer(allLayer[i].id);
      }

      this.map.flyTo({
        center: [106.4, 24.5],
        zoom: 4, // 缩放比例
      });
    },

    drawGeometry(item) {
      // debugger
      console.log(item);
      let self = this;
      let geometries;
      if (!item) return;

      if (item.type == "Feature") {
        self.showToCenter(item.geometry.coordinates);
        geometries = item.geometry;
      } else if (item.type == "Polygon") {
        self.showToCenter([item.coordinates]);
        geometries = item;
      } else if (item.type == "MultiPolygon") {
        self.showToCenter(item.coordinates);
        geometries = item;
      } else {
        geometries = item[0];
        self.showToCenter(item[0].coordinates);
      }

      if (item.length == 0) {
        self.resetMap();
      } else {
        if (self.map.getSource("maine") != null) {
          self.map.getSource("maine").setData(geometries);
        } else {
          self.map.addSource("maine", {
            type: "geojson",
            data: {
              type: "Feature",
              geometry: geometries,
            },
          });
          self.map.addLayer({
            id: "maine",
            type: "fill",
            source: "maine",
            layout: {},
            paint: {
              "fill-color": "#088",
              "fill-opacity": 0.5,
            },
          });
        }
      }
    },
    removeLayer(layerId) {
      if (this.map.getLayer(layerId)) {
        this.map.removeLayer(layerId);
      }
      if (this.map.getSource(layerId)) {
        this.map.removeSource(layerId);
      }
    },
    showToCenter(coordinates) {
      console.log(coordinates);
      // 计算 并 移动到中心点
      let minGlobalX = 180,
        minGlobalY = 90,
        maxGlobalX = -180,
        maxGlobalY = -90;

      for (let lineDatas of coordinates) {
        for (var i = 0; i < lineDatas.length; i++) {
          let gLineData = lineDatas[i];
          if (gLineData.length <= 0) continue;

          for (let j = 0; j < gLineData.length; j++) {
            if (minGlobalX > parseFloat(gLineData[j][0])) {
              minGlobalX = parseFloat(gLineData[j][0]);
            }
            if (maxGlobalX < parseFloat(gLineData[j][0])) {
              maxGlobalX = parseFloat(gLineData[j][0]);
            }
            if (minGlobalY > parseFloat(gLineData[j][1])) {
              minGlobalY = parseFloat(gLineData[j][1]);
            }
            if (maxGlobalY < parseFloat(gLineData[j][1])) {
              maxGlobalY = parseFloat(gLineData[j][1]);
            }
          }
        }
      }

      if (
        minGlobalX == 180 &&
        minGlobalY == 90 &&
        maxGlobalX == -180 &&
        maxGlobalY == -90
      ) {
        return;
      }

      let centerGlobalX = 0;
      let centerGlobalY = 0;
      if (maxGlobalX === -180 && minGlobalX === 180) {
        centerGlobalX = 116.4;
        centerGlobalY = 39.9;
      } else {
        centerGlobalX = (minGlobalX + maxGlobalX) / 2;
        centerGlobalY = (minGlobalY + maxGlobalY) / 2;
      }

      let centermoddle = [];
      centermoddle.push(centerGlobalX);
      centermoddle.push(centerGlobalY);
      //视图范围比数据范围大20%
      let viewWidth = 0;
      let viewHeight = 0;
      if (maxGlobalX === -180 && minGlobalX === 180) {
        viewWidth = (minGlobalX - maxGlobalX) * 1.2;
        viewHeight = (minGlobalY - maxGlobalY) * 1.2;
      } else {
        viewWidth = (maxGlobalX - minGlobalX) * 1.2;
        viewHeight = (maxGlobalY - minGlobalY) * 1.2;
      }

      let ratio = Math.sqrt(Math.sqrt(Math.sqrt(2))); //视图范围每扩大或缩小ratio倍，缩放等级对应减少或增加0.125

      let indexX = 6; //初始缩放等级为7
      let zoomBaseX = 5.96; //缩放等级为7时，经度范围为5.96
      if (viewWidth > zoomBaseX) {
        //如果实际范围比基准范围大，基准范围按比例扩大，直至大于实际范围，获取此时缩放等级
        while ((zoomBaseX = zoomBaseX * ratio) < viewWidth) {
          indexX -= 0.125;
        }
      } else {
        //如果实际范围比基准范围小，基准范围按比例缩小，直至小于实际范围，获取此时缩放等级
        while ((zoomBaseX = zoomBaseX / ratio) > viewWidth) {
          indexX += 0.125;
        }
      }

      let indexY = 6; //初始缩放等级为7
      let zoomBaseY = 1.91; //缩放等级为7时，纬度范围为1.91
      if (viewHeight > zoomBaseY) {
        while ((zoomBaseY = zoomBaseY * ratio) < viewHeight) {
          indexY -= 0.125;
        }
      } else {
        while ((zoomBaseY = zoomBaseY / ratio) > viewHeight) {
          indexY += 0.125;
        }
      }

      //在经纬度分别获取的缩放等级中，获取比较小的值作为缩放等级，确保数据能完全显示
      let index = indexX < indexY ? indexX : indexY;
      this.map.flyTo({
        center: centermoddle,
        zoom: index, // 缩放比例
      });
    },

    /**  以上为地图操作 */

    async produce(param) {
      await this.$refs.detailProduceTask.changeTask(param);
      console.log(param, "12");
      // Trigger popup window
      this.showPopup = true;
    },
    upDateLeaf(dir) {
      this.updateLeaf = dir;
      console.log(this.updateLeaf, " this.updateLeaf");
    },

    updateDir(dir) {
      this.imgDir = dir;
      //console.log(dir,'1')
    },
    updateNDVI(dir) {
      this.imgNDVI = dir;
    },
    updateLST(dir) {
      this.imgLST = dir;
    },
    dataPart(val) {
      this.$refs.detailProduceTask.getMerge(val);
    },
  },
  watch: {},
};
</script>

<style lang="scss">
#emergencyMonitor {
  display: flex;
  position: relative;

  height: calc(100% + 20px);
  margin: -10px;

  background-color: #ffffff;
}

#emergencyMonitor .ivu-drawer-body {
  padding: 0;
}

#emergencyMonitor .ivu-card {
  position: absolute;
  bottom: 0;
  width: 100%;

  z-index: 2;
}

#emergencyMonitor .ivu-card.no-expand {
  margin-left: 320px;
  width: calc(100vw - 320px);
}

#emergencyMonitor .iconBtn {
  height: 28px;
  margin: 6px;

  cursor: pointer;
}

#emergencyMonitor .iconBtn:hover {
  opacity: 0.6;
}
.iconBtn1 {
  height: 28px;
  margin: 6px;
  transform: rotate(270deg);
  cursor: pointer;
}

#emergencyMonitor .iconBtn1:hover {
  opacity: 0.6;
}
// Won't affect map layout as relative position
#emergencyMonitor .expandBtn {
  position: fixed;
  z-index: 2;

  display: flex;
  align-items: center;
  justify-content: center;

  height: 30px;
  width: 30px;
  margin: 6px;

  cursor: pointer;
}

#emergencyMonitor .taskImg {
  width: 30px;
  height: 30px;
  background: transparent;
  position: absolute;
  right: 2px;
  bottom: 35px;
}

.topButton {
  margin-top: 10px;
  position: absolute;
  left: 50%;
  top: 10px;
  margin-left: -150px;
  width: 445px;
  z-index: 100;
  display: flex;
  justify-content: space-between;
}
.dpMapControllWrapper {
  height: 100%;
  width: 100%;
  // #beforeMap {
  //   // width: 100% !important;
  //   height: calc(100vh - 100px);
  //   position: relative;
  //   border: 1px solid #ddd;
  //   border-top: none;
  // }
}
.map {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
}
/deep/.mapboxgl-compare {
  z-index: 0;
}

.info {
  z-index: 100;
  position: absolute;
  margin-top: 5px;

  right: 5%;
  top: 10px;
  width: 210px;

  display: flex;
  text-align: center;
  justify-content: center;

  font-size: 14px;
  background: black;
  opacity: 0.5;
  color: white;
}

.taskNameDiv {
  z-index: 100;
  position: absolute;
  margin-top: 5px;

  right: 18%;
  top: 10px;
  width: 220px;

  display: flex;
  text-align: center;
  justify-content: center;

  font-size: 14px;
  background: black;
  opacity: 0.5;
  color: white;
}
</style>
